package com.fakeDYChat.common.common.interceptor;

import com.fakeDYChat.common.common.exception.HttpErrorEnum;
import com.fakeDYChat.common.user.service.LoginService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTHORIZATION_SCHEMA = "Bearer ";
    public static final String UID = "uid";
    public static final String PUBLIC = "public";
    private final LoginService loginService;

    public TokenInterceptor(LoginService loginService) {
        this.loginService = loginService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        Long validUid = loginService.getValidUid(token);
        if (Objects.nonNull(validUid)) {
            request.setAttribute(UID, validUid);
        } else {
            boolean isPublic = isPublic(request);
            if (!isPublic) {
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }

    private static boolean isPublic(HttpServletRequest request) {
        //判断是否未public接口
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        return split.length > 3 && PUBLIC.equals(split[3]);
    }

    /**
     * 获取token
     **/
    private String getToken(HttpServletRequest request) {
        return request.getHeader(HEADER_AUTHORIZATION);
    }

}
